<template>
  <div class="allocation-page">
    <!-- 数据筛选 -->
    <el-card class="filter-card" shadow="never">
      <div class="filter-title">数据筛选</div>
      <el-form :inline="true" :model="filter" class="filter-form">
        <el-form-item label="调拨单号：">
          <el-input
            v-model="filter.AllocateId"
            placeholder="请输入/扫描单号"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="起始时间：">
          <el-date-picker
            v-model="filter.OrderCreatorTime"
            type="date"
            placeholder="起始时间"
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="单据状态：">
          <el-select
            v-model="filter.State"
            placeholder="请选择"
            style="width: 120px"
          >
            <el-option
              v-for="opt in statusOptions"
              :key="opt.value"
              :label="opt.label"
              :value="opt.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="ShowAllocation"
            ><el-icon> <Search /> </el-icon>查询</el-button
          >
          <el-button @click="handleReset"
            ><el-icon> <Refresh /> </el-icon>重置</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据列表操作栏 -->
    <el-card class="table-card" shadow="never">
      <div class="table-toolbar">
        <span class="table-title">调拨单列表</span>
        <div class="table-actions">
          <el-button type="primary" size="small" @click="openDialog">
            <el-icon><Plus /></el-icon>新增
          </el-button>
          <el-button size="small">
            <el-icon><Delete /></el-icon>删除
          </el-button>
          <el-button size="small">
            <el-icon><Download /></el-icon>导出
          </el-button>
          <el-button type="info" size="small" @click="testInventoryAPIs" style="margin-left: 8px;">
            <el-icon><InfoFilled /></el-icon>测试API
          </el-button>
        </div>
      </div>

      <!-- 数据表格 -->
      <el-table 
        :data="tableData" 
        border 
        style="width: 100%; margin-top: 10px; font-size: 12px;"
        :header-cell-style="{ textAlign: 'center', backgroundColor: '#f5f7fa', fontWeight: '500', fontSize: '12px', padding: '8px 0' }"
        :cell-style="{ textAlign: 'center', fontSize: '12px', padding: '6px 0' }"
        size="small"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="allocateId" label="调拨单号" min-width="120" align="center" />
        <el-table-column prop="orderNumber" label="关联订单号" min-width="120" align="center" />
        <el-table-column prop="allocateWarehouseIn" label="调拨仓库（入）" min-width="120" align="center" />
        <el-table-column prop="allocateWarehouseOut" label="调拨仓库（出）" min-width="120" align="center" />
        <el-table-column prop="orderCreator" label="制单人" min-width="100" align="center" />
        <el-table-column prop="orderCreatorTime" label="制单时间" min-width="140" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.orderCreatorTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态" min-width="100" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.state == 0" type="warning" size="small">待审核</el-tag>
            <el-tag v-if="scope.row.state == 1" type="info" size="small">已审核</el-tag>
            <el-tag v-if="scope.row.state == 2" type="danger" size="small">驳回</el-tag>
            <el-tag v-if="scope.row.state == 3" type="primary" size="small">待出库</el-tag>
            <el-tag v-if="scope.row.state == 4" type="success" size="small">已出库</el-tag>
            <el-tag v-if="scope.row.state == 5" type="primary" size="small">待入库</el-tag>
            <el-tag v-if="scope.row.state == 6" type="success" size="small">已入库</el-tag>
            <el-tag v-if="scope.row.state == 7" type="danger" size="small">已取消</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="manager" label="审核人" min-width="100" align="center" />
        <el-table-column prop="managerTime" label="审核时间" min-width="140" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.managerTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="note" label="备注" min-width="120" align="center" />
        <el-table-column label="操作" min-width="200" align="center">
          <template #default="scope">
            <el-link
              type="primary"
              @click="viewDialog(scope.row)"
              :underline="false"
              class="action-link"
            >查看</el-link>
            <el-link
              type="info"
              @click="getStatusInfo(scope.row.state)"
              :underline="false"
              class="action-link"
            >状态</el-link>
            <el-link
              v-if="canEditOrDelete(scope.row)"
              type="primary"
              @click="editDialog(scope.row)"
              :underline="false"
              class="action-link"
            >编辑</el-link>
            <el-link
              v-if="canEditOrDelete(scope.row)"
              type="primary"
              @click="DelProduct(scope.row)"
              :underline="false"
              class="action-link"
            >删除</el-link>
            <el-link
              v-if="scope.row.state == 1 && canOutboundInbound(scope.row)"
              type="success"
              @click="createOutboundRecord(scope.row)"
              :underline="false"
              class="action-link"
            >出库</el-link>
            <el-link
              v-if="(scope.row.state == 4 || scope.row.state == 5) && canOutboundInbound(scope.row)"
              type="warning"
              @click="createInboundRecord(scope.row)"
              :underline="false"
              class="action-link"
            >入库</el-link>
            <el-link v-if="userRid==13 && scope.row.state == 0" type="success" @click="openApproveDialog(scope.row)" :underline="false" class="action-link">审批</el-link>
          </template>
        </el-table-column>
      </el-table>

      <!-- 批量操作栏和分页 -->
      <div class="table-footer">
        <div class="batch-actions">
          <el-button size="small">全选</el-button>
          <el-button size="small">反选</el-button>
          <el-select size="small" placeholder="批量操作" style="width: 120px">
            <el-option label="批量删除" value="delete" />
            <el-option label="批量导出" value="export" />
          </el-select>
        </div>
        <div class="demo-pagination-block">
          <el-pagination
            v-model:current-page="Total.PageIndex"
            v-model:page-size="Total.PageSize"
            :page-sizes="[15, 30, 45, 60]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="Total.totalCount"
            @current-change="handlePageChange"
            @size-change="handleSizeChange"
          />
        </div>
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="isEditMode ? '编辑调拨单' : '新增调拨单'" width="80%">
      <el-form :model="allocationForm" label-width="100px">

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="调拨单号">
              <el-input
                v-model="allocationForm.allocateId"
                placeholder="自动生成"
                :disabled="isEditMode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="调拨仓库（入）" required>
              <el-select
                v-model="allocationForm.allocateWarehouseIn"
                placeholder="请选择调拨仓库（入）"
                filterable
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in depotOptions"
                  :key="item?.depotId || item?.depotName || Math.random()"
                  :label="item?.depotName || '未知仓库'"
                  :value="item?.depotName || ''"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="调拨仓库（出）" required>
              <el-select
                v-model="allocationForm.allocateWarehouseOut"
                placeholder="请选择调拨仓库（出）"
                filterable
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in depotOptions"
                  :key="item?.depotId || item?.depotName || Math.random()"
                  :label="item?.depotName || '未知仓库'"
                  :value="item?.depotName || ''"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="关联订单号">
              <el-input 
                v-model="allocationForm.orderNumber" 
                :disabled="!isEditMode"
                :placeholder="isEditMode ? '编辑时可修改' : '自动生成'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="制单人">
              <el-input 
                v-model="allocationForm.orderCreator" 
                :disabled="true"
                :placeholder="isEditMode ? '制单人不可修改' : '自动填充当前登录用户'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制单时间">
              <el-date-picker
                v-model="allocationForm.orderCreatorTime"
                type="date"
                placeholder="请选择日期"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input
            v-model="allocationForm.note"
            type="textarea"
            :rows="3"
            maxlength="300"
            show-word-limit
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <div style="margin: 20px 0 10px 0; font-weight: bold">产品信息</div>
      <div style="margin-bottom: 10px">
        <el-button type="primary" size="small" @click="fetchProducts"
          >新增产品</el-button
        >
      </div>
      <el-table :data="allocationProductForm" border>
        <el-table-column prop="id" label="产品ID" width="100">
          <template #default="scope">
            <div>
              <div
                v-if="scope.row.productId || scope.row.id"
                style="color: #409eff"
              >
                ID: {{ scope.row.productId || scope.row.id }}
              </div>
              <div v-else style="color: #f56c6c">缺失</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="产品名称" />
        <el-table-column prop="productCode" label="产品编码" />
        <el-table-column prop="specifications" label="规格" />
        <el-table-column label="数量">
          <template #default="scope">
            <el-input
              v-model="scope.row.quantity"
              type="number"
              min="0"
              style="width: 80px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="locationName" label="库位" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-link type="danger" @click="removeProductFromForm(scope.$index)"
              >删除</el-link
            >
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: right; margin-top: 10px">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitForm">{{ isEditMode ? '更新' : '提交' }}</el-button>
      </div>
    </el-dialog>

    <!-- 产品选择弹框 -->
    <el-dialog
      v-model="productDialogVisible"
      :title="isEditMode && allocationProductForm.length > 0 ? `选择产品 (当前调拨单包含 ${allocationProductForm.length} 个产品)` : '选择产品'"
      width="80%"
      :close-on-click-modal="false"
    >
      <!-- 编辑模式提示 -->
      <div v-if="isEditMode && allocationProductForm.length > 0" style="margin-bottom: 15px; padding: 10px; background-color: #f0f9ff; border: 1px solid #b3d8ff; border-radius: 4px;">
        <el-icon style="color: #409eff; margin-right: 5px;"><InfoFilled /></el-icon>
        <span style="color: #409eff; font-size: 14px;">
          编辑模式：已自动勾选当前调拨单中的产品，您可以添加新产品或取消勾选不需要的产品
        </span>
      </div>
      
      <!-- 当前调拨单产品列表 -->
      <div v-if="isEditMode && allocationProductForm.length > 0" style="margin-bottom: 15px;">
        <div style="font-weight: bold; margin-bottom: 8px; color: #606266;">当前调拨单包含的产品：</div>
        <div style="display: flex; flex-wrap: wrap; gap: 8px;">
          <el-tag 
            v-for="product in allocationProductForm" 
            :key="product.id || product.productId"
            type="info" 
            size="small"
            style="margin-bottom: 4px;"
          >
            {{ product.productName }} ({{ product.productCode }})
          </el-tag>
        </div>
      </div>
      
      <el-table
        :data="productList"
        border
        style="width: 100%"
        @selection-change="(selection) => (selectedProducts = selection)"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="产品ID" width="80">
          <template #default="scope">
            <span v-if="scope.row.id" style="color: #409eff">
              {{ scope.row.id }}
            </span>
            <span v-else style="color: #f56c6c">缺失</span>
          </template>
        </el-table-column>
        <el-table-column prop="productCode" label="产品编码" width="120" />
        <el-table-column prop="productName" label="产品名称" width="160" />
        <el-table-column prop="specifications" label="规格" width="100" />
        <el-table-column prop="stock" label="库存" width="80">
          <template #default="scope">
            {{ scope.row.stock || scope.row.inventory || scope.row.stockQuantity || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="locationName" label="库位" width="120">
          <template #default="scope">
            {{ scope.row.locationName || scope.row.location || scope.row.warehouse || '默认库位' }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述">
          <template #default="scope">
            {{ scope.row.description || scope.row.desc || scope.row.remark || scope.row.note || '-' }}
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelSelectProducts">取消</el-button>
          <el-button
            type="primary"
            @click="confirmSelectProducts"
            :disabled="selectedProducts.length === 0"
          >
            确认选择 ({{ selectedProducts.length }})
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看弹框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="调拨单详情"
      width="90%"
      :close-on-click-modal="false"
    >
      <!-- 基本信息 -->
      <div class="view-dialog-content">
        <div class="info-section">
          <div class="info-row">
            <div class="info-item">
              <span class="info-label">调拨单号：</span>
              <span class="info-value">{{ viewData.allocateId || "-" }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">单据状态：</span>
              <span class="info-value">
                <el-tag v-if="viewData.state == 0" type="warning">待审核</el-tag>
                <el-tag v-if="viewData.state == 1" type="info">已审核</el-tag>
                <el-tag v-if="viewData.state == 2" type="primary">待出库</el-tag>
                <el-tag v-if="viewData.state == 3" type="success">已出库</el-tag>
                <el-tag v-if="viewData.state == 4" type="primary">待入库</el-tag>
                <el-tag v-if="viewData.state == 5" type="success">已入库</el-tag>
                <el-tag v-if="viewData.state == 6" type="danger">已取消</el-tag>
              </span>
            </div>
          </div>
          <div class="info-row">
            <div class="info-item">
              <span class="info-label">关联单号：</span>
              <span class="info-value">{{ viewData.orderNumber || "-" }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">制单人：</span>
              <span class="info-value">{{ viewData.orderCreator || "-" }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">制单日期：</span>
              <span class="info-value">{{
                formatDate(viewData.orderCreatorTime) || "-"
              }}</span>
            </div>
          </div>
          <div class="info-row">
            <div class="info-item full-width">
              <span class="info-label">备注：</span>
              <span class="info-value">{{ viewData.note || "无" }}</span>
            </div>
          </div>
          <div class="info-row">
            <div class="info-item full-width">
              <span class="info-label">审核原因：</span>
              <span class="info-value">{{
                viewData.auditReason || "同意"
              }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 标签页 -->
      <el-tabs v-model="activeTab" type="border-card" style="margin-top: 20px;">
        <el-tab-pane label="产品信息" name="products">
          <div style="margin-bottom: 10px; text-align: right;">
            <el-button type="primary" size="small" @click="exportProductInfo">
              <el-icon><Download /></el-icon>导出产品信息
            </el-button>
            <el-button type="success" size="small" @click="exportCompleteReport" style="margin-left: 8px;">
              <el-icon><Download /></el-icon>导出完整报告
            </el-button>
          </div>
          <el-table 
            :data="viewProductData" 
            border 
            style="width: 100%; font-size: 12px;" 
            class="record-table"
            :header-cell-style="{ textAlign: 'center', backgroundColor: '#f5f7fa', fontWeight: '500', fontSize: '12px', padding: '8px 0' }"
            :cell-style="{ textAlign: 'center', fontSize: '12px', padding: '6px 0' }"
            size="small"
          >
            <el-table-column
              prop="productCode"
              label="产品编码"
              min-width="120"
              align="center"
            />
            <el-table-column
              prop="productName"
              label="产品名称"
              min-width="160"
              align="center"
            />
            <el-table-column
              prop="specifications"
              label="规格"
              min-width="100"
              align="center"
            />
            <el-table-column
              prop="batch"
              label="批次"
              min-width="120"
              align="center"
            />
            <el-table-column
              prop="quantity"
              label="数量"
              min-width="100"
              align="center"
            />
            <el-table-column
              prop="currentLocation"
              label="当前库位"
              min-width="140"
              align="center"
            />
            <el-table-column
              prop="targetLocation"
              label="调拨仓库"
              min-width="140"
              align="center"
            />
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="出库记录" name="outbound">
          <div style="margin-bottom: 10px; text-align: right;">
            <el-button type="info" size="small" @click="debugOutboundRecords" style="margin-right: 8px;">
              <el-icon><InfoFilled /></el-icon>调试出库记录
            </el-button>
            <el-button type="primary" size="small" @click="exportOutboundRecords">
              <el-icon><Download /></el-icon>导出出库记录
            </el-button>
          </div>
          <el-table 
            :data="outboundRecords" 
            border 
            style="width: 100%; font-size: 12px;" 
            class="record-table"
            :header-cell-style="{ textAlign: 'center', backgroundColor: '#f5f7fa', fontWeight: '500', fontSize: '12px', padding: '8px 0' }"
            :cell-style="{ textAlign: 'center', fontSize: '12px', padding: '6px 0' }"
            size="small"
          >
            <el-table-column prop="associatedOrderNumber" label="关联订单号" min-width="120" align="center" />
            <el-table-column prop="preparedName" label="制单人" min-width="100" align="center" />
            <el-table-column prop="preparedTime" label="制单时间" min-width="160" align="center">
              <template #default="scope">
                {{ formatDate(scope.row.preparedTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="产品名称" min-width="160" align="center" />
            <el-table-column prop="price" label="商品单价" min-width="100" align="center">
              <template #default="scope">
                ¥{{ scope.row.price || 0 }}
              </template>
            </el-table-column>
            <el-table-column prop="incomingQuantity" label="库存数量" min-width="100" align="center" />
            <el-table-column prop="depotName" label="仓库名称" min-width="120" align="center" />
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="入库记录" name="inbound">
          <div style="margin-bottom: 10px; text-align: right;">
            <el-button type="info" size="small" @click="debugInboundRecords" style="margin-right: 8px;">
              <el-icon><InfoFilled /></el-icon>调试入库记录
            </el-button>
            <el-button type="primary" size="small" @click="exportInboundRecords">
              <el-icon><Download /></el-icon>导出入库记录
            </el-button>
          </div>
          <el-table 
            :data="inboundRecords" 
            border 
            style="width: 100%; font-size: 12px;" 
            class="record-table"
            :header-cell-style="{ textAlign: 'center', backgroundColor: '#f5f7fa', fontWeight: '500', fontSize: '12px', padding: '8px 0' }"
            :cell-style="{ textAlign: 'center', fontSize: '12px', padding: '6px 0' }"
            size="small"
          >
            <el-table-column prop="associatedOrderNumber" label="关联订单号" min-width="120" align="center" />
            <el-table-column prop="preparedName" label="制单人" min-width="100" align="center" />
            <el-table-column prop="preparedTime" label="制单时间" min-width="160" align="center">
              <template #default="scope">
                {{ formatDate(scope.row.preparedTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="产品名称" min-width="160" align="center" />
            <el-table-column prop="price" label="商品单价" min-width="100" align="center">
              <template #default="scope">
                ¥{{ scope.row.price || 0 }}
              </template>
            </el-table-column>
            <el-table-column prop="incomingQuantity" label="库存数量" min-width="100" align="center" />
            <el-table-column prop="depotName" label="仓库名称" min-width="120" align="center" />
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="操作记录" name="operation">
          <!-- 搜索和筛选区域 -->
          <div style="margin-bottom: 15px; padding: 15px; background-color: #f8f9fa; border-radius: 4px;">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="操作类型" style="margin-bottom: 0;">
                  <el-select v-model="operationFilter.operationType" placeholder="请选择" style="width: 100%;" clearable>
                    <el-option label="全部" value="" />
                    <el-option label="新增" value="新增" />
                    <el-option label="修改" value="修改" />
                    <el-option label="删除" value="删除" />
                    <el-option label="导出" value="导出" />
                    <el-option label="打印" value="打印" />
                    <el-option label="暂存" value="暂存" />
                    <el-option label="审核通过" value="审核通过" />
                    <el-option label="审核驳回" value="审核驳回" />
                    <el-option label="审批" value="审批" />
                    <el-option label="出库" value="出库" />
                    <el-option label="入库" value="入库" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="操作人" style="margin-bottom: 0;">
                  <el-input v-model="operationFilter.operator" placeholder="请输入操作人" style="width: 100%;" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="操作时间" style="margin-bottom: 0;">
                  <el-date-picker
                    v-model="operationFilter.operationTime"
                    type="datetime"
                    placeholder="请选择操作时间"
                    style="width: 100%;"
                    clearable
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <div style="display: flex; gap: 10px; align-items: flex-end; height: 100%;">
                  <el-button type="primary" @click="searchOperationRecords">
                    <el-icon><Search /></el-icon>查询
                  </el-button>
                  <el-button @click="resetOperationFilter">
                    <el-icon><Refresh /></el-icon>重置
                  </el-button>
                </div>
              </el-col>
            </el-row>
          </div>
          
          <!-- 操作按钮区域 -->
          <div style="margin-bottom: 10px; text-align: left;">
            <el-button type="primary" size="small" @click="exportOperationRecords">
              <el-icon><Download /></el-icon>导出操作记录
            </el-button>
            <el-button type="info" size="small" @click="debugOperationRecords" style="margin-left: 8px;">
              <el-icon><InfoFilled /></el-icon>调试操作记录
            </el-button>
          </div>
          
          <!-- 操作记录表格 -->
          <el-table 
            :data="filteredOperationRecords" 
            border 
            style="width: 100%; font-size: 12px;" 
            class="operation-record-table"
            :header-cell-style="{ textAlign: 'center', backgroundColor: '#fafafa', fontWeight: '500', fontSize: '12px', padding: '8px 0', borderBottom: '1px solid #ebeef5' }"
            :cell-style="{ textAlign: 'center', fontSize: '12px', padding: '8px 0', borderBottom: '1px solid #ebeef5' }"
            size="small"
            v-loading="operationRecordsLoading"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="operator" label="操作人" min-width="100" align="center" />
            <el-table-column prop="operationType" label="操作类型" min-width="100" align="center" />
            <el-table-column prop="operationContent" label="操作内容描述" min-width="200" align="center" />
            <el-table-column prop="createTime" label="操作时间" min-width="160" align="center">
              <template #default="scope">
                {{ formatDate(scope.row.createTime) }}
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页区域 -->
          <div style="margin-top: 15px; display: flex; justify-content: space-between; align-items: center;">
            <div style="color: #606266;">
              <span>总{{ operationRecords.length }}条</span>
              <span v-if="operationFilter.operationType || operationFilter.operator || operationFilter.operationTime" style="margin-left: 10px; color: #409eff;">
                (筛选后: {{ getFilteredTotalCount() }}条)
              </span>
            </div>
            <el-pagination
              v-model:current-page="operationPagination.currentPage"
              v-model:page-size="operationPagination.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :background="true"
              layout="total, sizes, prev, pager, next, jumper"
              :total="getFilteredTotalCount()"
              @current-change="handleOperationPageChange"
              @size-change="handleOperationSizeChange"
            />
          </div>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeViewDialog">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审批弹框 -->
    <el-dialog v-model="approveDialogVisible" title="审批" width="500px">
      <div v-if="approveDialogRow">
        <div style="margin-bottom: 10px; font-weight: bold;">调拨单信息</div>
        <el-descriptions :column="1" border size="small">
          <el-descriptions-item label="调拨单号">{{ approveDialogRow.allocateId }}</el-descriptions-item>
          <el-descriptions-item label="关联订单号">{{ approveDialogRow.orderNumber }}</el-descriptions-item>
          <el-descriptions-item label="调拨仓库（入）">{{ approveDialogRow.allocateWarehouseIn }}</el-descriptions-item>
          <el-descriptions-item label="调拨仓库（出）">{{ approveDialogRow.allocateWarehouseOut }}</el-descriptions-item>
          <el-descriptions-item label="制单人">{{ approveDialogRow.orderCreator }}</el-descriptions-item>
          <el-descriptions-item label="制单时间">{{ formatDate(approveDialogRow.orderCreatorTime) }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{ approveDialogRow.note }}</el-descriptions-item>
        </el-descriptions>
        <el-form label-width="80px" style="margin-top: 18px;">
          <el-form-item label="审批备注">
            <el-input v-model="approveRemark" type="textarea" :rows="2" placeholder="请输入审批意见（可选）" />
          </el-form-item>
        </el-form>
        <div style="text-align: right; margin-top: 18px;">
          <el-button @click="approveDialogVisible=false">取消</el-button>
          <el-button type="danger" @click="handleApprove('reject')">驳回</el-button>
          <el-button type="primary" @click="handleApprove('agree')">同意</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick, computed } from "vue";
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElButton,
  ElTable,
  ElTableColumn,
  ElPagination,
  ElSelect,
  ElOption,
  ElDatePicker,
  ElCard,
  ElLink,
  ElIcon,
  ElRow,
  ElCol,
  ElDialog,
  ElMessageBox,
  ElMessage,
  ElTag,
  ElTabs,
  ElTabPane,
  ElDescriptions,
  ElDescriptionsItem,
} from "element-plus";
import {
  Search,
  Refresh,
  Plus,
  Delete,
  Download,
  InfoFilled,
} from "@element-plus/icons-vue";

import { allread, allwrite } from "@/systeamaxios/sysaxiosHelpers";
import axios from "axios";
import { useCounterStore } from "@/stores/counter";
import http from "@/http/axiosHelper"

// 声明XLSX全局类型
declare global {
  interface Window {
    XLSX: any;
  }
}

// API配置管理
const API_CONFIG = {
  PRODUCT_API: {
    baseURL: "http://112.126.93.146:8000",
    timeout: 5000,
    retries: 3
  }
};

// 创建产品API的axios实例
const productApi = axios.create({
  baseURL: API_CONFIG.PRODUCT_API.baseURL,
  timeout: API_CONFIG.PRODUCT_API.timeout,
});

// 统一的产品错误处理函数
const handleProductError = (error: any, attempt: number, maxAttempts: number) => {
  console.error(`产品API错误 (第${attempt}次):`, error);
  
  if (attempt === maxAttempts) {
    if (error.response) {
      const status = error.response.status;
      if (status === 404) {
        ElMessage.error("产品API接口不存在，请检查服务器配置");
      } else {
        ElMessage.error(
          `获取产品数据失败 (${status}): ${
            error.response.data?.message || error.response.statusText
          }`
        );
      }
    } else if (error.request) {
      ElMessage.error(
        "无法连接到产品服务器，请检查服务器状态"
      );
    } else {
      ElMessage.error(`获取产品数据失败: ${error.message}`);
    }
  }
};

// 尝试备用端点的函数
const tryAlternativeEndpoint = async (endpoint: string) => {
  try {
    console.log(`尝试备用端点: ${endpoint}`);
    const response = await productApi.get(endpoint);
    return response.data;
  } catch (error) {
    console.error(`备用端点 ${endpoint} 失败:`, error);
    return null;
  }
};

// 测试库存API
const testInventoryAPIs = async () => {
  console.log("=== 测试库存API ===");
  
  try {
    // 测试出库记录API
    console.log("测试出库记录API...");
    const outboundResponse = await http.get("/read/api/Inventory/Getchuku");
    console.log("出库记录API响应:", outboundResponse.data);
    
    if (outboundResponse.data.code === 200) {
      const outboundData = outboundResponse.data.data || [];
      console.log("出库记录数据:", outboundData);
      console.log("出库记录数量:", outboundData.length);
      
      // 显示前几条记录的关键字段
      outboundData.slice(0, 3).forEach((item: any, index: number) => {
        console.log(`出库记录${index + 1}:`, {
          associatedOrderNumber: item.associatedOrderNumber,
          preparedName: item.preparedName,
          productName: item.productName,
          depotName: item.depotName
        });
      });
    }
    
    // 测试入库记录API
    console.log("测试入库记录API...");
    const inboundResponse = await http.get("/read/api/Inventory/GetOutbound");
    console.log("入库记录API响应:", inboundResponse.data);
    
    if (inboundResponse.data.code === 200) {
      const inboundData = inboundResponse.data.data || [];
      console.log("入库记录数据:", inboundData);
      console.log("入库记录数量:", inboundData.length);
      
      // 显示前几条记录的关键字段
      inboundData.slice(0, 3).forEach((item: any, index: number) => {
        console.log(`入库记录${index + 1}:`, {
          associatedOrderNumber: item.associatedOrderNumber,
          preparedName: item.preparedName,
          productName: item.productName,
          depotName: item.depotName
        });
      });
    }
    
    ElMessage.success("API测试完成，请查看控制台");
  } catch (error) {
    console.error("API测试失败:", error);
    ElMessage.error("API测试失败，请查看控制台");
  }
};


const depotOptions = ref<{ depotId: string; depotName: string }[]>([]);
const fetchDepotOptions = async () => {
  try {
    const res = await http.get("/basicread/api/Depot/GetDepot");
    const rawData = res.data.data || res.data || [];
    
    // 过滤掉null或undefined的项，确保每个项都有有效的depotId和depotName
    depotOptions.value = rawData.filter((item: any) => 
      item && 
      typeof item === 'object' && 
      (item.depotId || item.depotName)
    );
    
    console.log('仓库选项加载成功:', depotOptions.value);
  } catch (e) {
    console.error('加载仓库选项失败:', e);
    depotOptions.value = [];
  }
};

// 初始化Pinia store
const counterStore = useCounterStore();

onMounted(() => {
  fetchDepotOptions();
  ShowAllocation();
  
  // 监听store中的用户信息变化，自动更新localStorage
  if (counterStore.Account && counterStore.Account.name) {
    localStorage.setItem('currentUser', counterStore.Account.name);
  }
});

// 监听store中的用户信息变化
watch(() => counterStore.Account.name, (newName) => {
  if (newName) {
    localStorage.setItem('currentUser', newName);
    console.log('用户信息已更新:', newName);
  }
});

const filter = ref({
  AllocateId: "",
  OrderCreatorTime: "",
  State: "",
});
const statusOptions = [
  { label: "请选择", value: "" },
  { label: "待审核", value: "0" },
  { label: "已审核", value: "1" },
  { label: "驳回", value: "2" },
  { label: "待出库", value: "3" },
  { label: "已出库", value: "4" },
  { label: "待入库", value: "5" },
  { label: "已入库", value: "6" },
  { label: "已取消", value: "7" },
];
const Total = ref({
  PageSize: 15,
  PageIndex: 1,
  totalCount: 1,
  totalPage: 1,
});
const tableData = ref<any[]>([]);
const ShowAllocation = () => {
  http
    .get("/lssueread/api/Allocate/GetAllocate", {
      params: {
        PageIndex: Total.value.PageIndex,
        PageSize: Total.value.PageSize,
        AllocateId: filter.value.AllocateId,
        OrderCreatorTime: filter.value.OrderCreatorTime,
        State: filter.value.State,
      },
    })
    .then((res) => {
      console.log("主表格API返回的数据:", res.data);
      console.log("主表格数据项示例:", res.data.pageDatas?.[0]);
      
      // 对调拨单号进行去重，每个调拨单号只保留一条记录
      // 这样可以避免同一个调拨单因为包含多个产品而重复显示
      const rawList = res.data.pageDatas || [];
      const uniqueList = [];
      const seen = new Set();
      
      for (const item of rawList) {
        if (!seen.has(item.allocateId)) {
          // 确保每个记录都有id字段
          const recordWithId = {
            ...item,
            id: item.id || item.Id || item.allocateId // 优先使用id，如果没有则使用allocateId作为备用
          };
          uniqueList.push(recordWithId);
          seen.add(item.allocateId);
        }
      }
      
      console.log("去重前记录数:", rawList.length);
      console.log("去重后记录数:", uniqueList.length);
      console.log("去重后第一条记录的id字段:", uniqueList[0]?.id);
      console.log("去重后第一条记录的所有字段:", uniqueList[0] ? Object.keys(uniqueList[0]) : []);
      
      // 计算分页
      const startIndex = (Total.value.PageIndex - 1) * Total.value.PageSize;
      const endIndex = startIndex + Total.value.PageSize;
      const paginatedList = uniqueList.slice(startIndex, endIndex);
      
      tableData.value = paginatedList;
      Total.value.totalCount = uniqueList.length; // 总数为去重后的数量
      Total.value.totalPage = Math.ceil(uniqueList.length / Total.value.PageSize);
    });
};
const handleReset = () => {
  filter.value = { AllocateId: "", OrderCreatorTime: "", State: "" };
};

// 分页处理函数
const handlePageChange = (page: number) => {
  Total.value.PageIndex = page;
  ShowAllocation();
};

const handleSizeChange = (size: number) => {
  Total.value.PageSize = size;
  Total.value.PageIndex = 1; // 重置到第一页
  ShowAllocation();
};
const DelProduct = (allocateId: any) => {
  console.log("删除调拨单，AllocateId:", allocateId.allocateId);

  if (!allocateId.allocateId) {
    ElMessage.error("调拨单号不能为空");
    return;
  }

  // 权限验证：只有制单人才能删除，且不能删除已审核或驳回的调拨单
  if (!canEditOrDelete(allocateId)) {
    if (allocateId.state === 1) {
      ElMessage.error("已审核的调拨单无法删除");
    } else if (allocateId.state === 2) {
      ElMessage.error("驳回的调拨单无法删除");
    } else {
      ElMessage.error("您没有权限删除此调拨单，只有制单人才能删除");
    }
    return;
  }

  ElMessageBox.confirm("此操作将永久删除该数据，是否继续？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      console.log("发送删除请求，调拨单号:", allocateId.allocateId);
      http
        .get("/lssueread/api/Allocate/DelAllocate", {
          params: { AllocateId: allocateId.allocateId }
        })
        .then(async (res) => {
          console.log("删除响应:", res.data);
          if (res.data.code == 200) {
            ElMessage.success(res.data.message);
            

            
            ShowAllocation();
          } else {
            ElMessage.warning(res.data.message);
          }
        })
        .catch((err) => {
          console.error("删除请求失败:", err);
          ElMessage.error("删除失败，请重试");
        });
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 定义产品相关的类型接口
interface Product {
  id?: string | number;
  productCode?: string;
  productName?: string;
  specifications?: string;
  price?: number;
  stock?: number;
  locationName?: string;
  [key: string]: any;
}

interface AllocationProduct {
  productName: string;
  productCode: string;
  specifications: string;
  quantity: number;
  locationName: string;
  id?: string | number;
  productId?: string | number;
}

// 定义API需要的ProductItem接口
interface ProductItem {
  productId: number;
  quantity: number;
  productCode: string;
}

// 定义调拨单请求接口
interface AllocationRequest {
  allocateId: string;
  orderNumber: string;
  allocateWarehouseIn: string;
  allocateWarehouseOut: string;
  products: ProductItem[];
  note?: string;
  orderCreator?: string;
  orderCreatorTime: string;
  manager?: string;
  managerTime?: string | null;
  state: number;
}

// 定义查看数据的类型接口
interface ViewData {
  allocateId?: string;
  state?: number;
  orderNumber?: string;
  orderCreator?: string;
  orderCreatorTime?: string;
  note?: string;
  auditReason?: string;
  [key: string]: any;
}

interface ViewProductData {
  productCode?: string;
  productName?: string;
  specifications?: string;
  batch?: string;
  quantity?: string;
  currentLocation?: string;
  targetLocation?: string;
}

const dialogVisible = ref(false);
const viewDialogVisible = ref(false);
const viewData = ref<ViewData>({});
const viewProductData = ref<ViewProductData[]>([]);
const activeTab = ref('products');
const isEditMode = ref(false); // 添加编辑模式标志
const outboundRecords = ref<any[]>([]);
const inboundRecords = ref<any[]>([]);
const operationRecords = ref<any[]>([]);

// 操作记录筛选和分页
const operationFilter = ref({
  operationType: '',
  operator: '',
  operationTime: ''
});

// 筛选后的操作记录
const filteredOperationRecords = ref<any[]>([]);

const operationPagination = ref({
  currentPage: 1,
  pageSize: 10,
  totalCount: 0
});

const operationRecordsLoading = ref(false);

const allocationForm = ref({
  allocateId: "",
  orderNumber: "",
  allocateWarehouseIn: "",
  allocateWarehouseOut: "",
  products: [
    {
      productCode: "",
      quantity: "",
    },
  ],
  note: "",
  orderCreator: "",
  orderCreatorTime: "2025-07-24T11:43:24.446Z",
  manager: "",
  managerTime: null,
  state: 0,
});
const openDialog = () => {
  // 生成当前时间的调拨单号（时分秒）
  const now = new Date();
  const pad = (n: number) => n.toString().padStart(2, "0");
  const allocateId =
    pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds());

  // 生成关联订单号（年月日时分秒）
  const year = now.getFullYear();
  const month = pad(now.getMonth() + 1);
  const day = pad(now.getDate());
  const hour = pad(now.getHours());
  const minute = pad(now.getMinutes());
  const second = pad(now.getSeconds());
  const orderNumber = `TB${year}${month}${day}${hour}${minute}${second}`;

  // 格式化当前时间为ISO字符串
  const currentTime = now.toISOString();

  // 获取当前登录用户
  const currentUser = getCurrentUser();
  console.log('新增调拨单 - 当前用户:', currentUser);
  console.log('Store中的用户信息:', counterStore.Account);
  console.log('localStorage中的用户信息:', localStorage.getItem('currentUser'));
  console.log('自动生成的关联订单号:', orderNumber);

  allocationForm.value = {
    allocateId: allocateId,
    orderNumber: orderNumber, // 自动生成的关联订单号
    allocateWarehouseIn: "",
    allocateWarehouseOut: "",
    products: [],
    note: "",
    orderCreator: currentUser, // 自动填充当前登录用户
    orderCreatorTime: currentTime,
    manager: "",
    managerTime: null,
    state: 0,
  };
  
  console.log('设置后的表单数据:', allocationForm.value);
  allocationProductForm.value = [];
  isEditMode.value = false; // 设置为新增模式
  dialogVisible.value = true;
};
const closeDialog = () => {
  dialogVisible.value = false;
  // 清理数据
  allocationProductForm.value = [];
  allocationForm.value = {
    allocateId: "",
    orderNumber: "",
    allocateWarehouseIn: "",
    allocateWarehouseOut: "",
    products: [],
    note: "",
    orderCreator: "", // 重置制单人字段
    orderCreatorTime: new Date().toISOString(),
    manager: "",
    managerTime: null,
    state: 0,
  };
  isEditMode.value = false;
};
// 新增：编辑弹窗方法
const editDialog = async (row: any) => {
  console.log("编辑弹窗接收到的行数据:", row);
      console.log("行数据中的allocateId字段:", row.allocateId);
  console.log("行数据中的所有字段:", Object.keys(row));
  
  // 权限验证：只有制单人才能编辑，且不能编辑已审核或驳回的调拨单
  if (!canEditOrDelete(row)) {
    if (row.state === 1) {
      ElMessage.error("已审核的调拨单无法编辑");
    } else if (row.state === 2) {
      ElMessage.error("驳回的调拨单无法编辑");
    } else {
      ElMessage.error("您没有权限编辑此调拨单，只有制单人才能编辑");
    }
    return;
  }
  
  // 获取当前登录用户
  const currentUser = getCurrentUser();
  console.log('编辑调拨单 - 当前用户:', currentUser);
  console.log('原有制单人:', row.orderCreator);
  
  // 设置表单数据
  allocationForm.value = {
    allocateId: row.allocateId || "",
    orderNumber: row.orderNumber || "",
    allocateWarehouseIn: row.allocateWarehouseIn || "",
    allocateWarehouseOut: row.allocateWarehouseOut || "",
    products: [],
    note: row.note || "",
    orderCreator: row.orderCreator || currentUser, // 如果原有制单人为空，则使用当前用户
    orderCreatorTime: row.orderCreatorTime || new Date().toISOString(),
    manager: row.manager || "",
    managerTime: row.managerTime || null,
    state: row.state || 0,
  };
  
  console.log("设置表单数据完成");
  
  // 获取产品数据
  await ShowAllocationProduct(row.allocateId);
  isEditMode.value = true; // 设置为编辑模式
  console.log("设置编辑模式，isEditMode:", isEditMode.value);
  dialogVisible.value = true;
};
const allocationProductForm = ref<AllocationProduct[]>([]);
const ShowAllocationProduct = async (allocateId: string) => {
  console.log("获取编辑产品数据，调拨单号:", allocateId);
  
  // 直接尝试从原始数据中获取该调拨单的所有产品
  console.log("从原始数据获取产品信息");
  
  try {
    // 获取所有调拨单数据（不去重）
    const response = await http.get("/lssueread/api/Allocate/GetAllocate", {
      params: {
        PageIndex: 1,
        PageSize: 1000, // 获取足够多的数据
        AllocateId: allocateId,
      },
    });
    
    console.log("获取原始调拨单数据:", response.data);
    const rawList = response.data.pageDatas || [];
    
    // 筛选出属于当前调拨单的所有产品
    const productsForThisAllocate = rawList.filter((item: any) => item.allocateId === allocateId);
    console.log(`找到 ${productsForThisAllocate.length} 个产品属于调拨单 ${allocateId}`);
    
    if (productsForThisAllocate.length > 0) {
      // 将原始数据转换为编辑格式
      allocationProductForm.value = productsForThisAllocate.map((item: any, index: number) => ({
        productName: item.productName || item.name || `产品${index + 1}`,
        productCode: item.productCode || item.code || `CP${index + 1}`,
        specifications: item.specifications || item.spec || "个",
        quantity: item.quantity || 1,
        locationName: item.locationName || item.location || item.warehouse || "默认库位",
        id: item.id || item.productId || index + 1,
        productId: item.productId || item.id || index + 1,
      }));
      console.log("从原始数据创建的编辑产品列表:", allocationProductForm.value);
      return;
    }
  } catch (error) {
    console.error("获取原始数据失败:", error);
  }
  
  // 如果还是无法获取，显示空数据
  console.log("无法获取产品数据，显示空数据");
  allocationProductForm.value = [];
  ElMessage.warning("无法获取产品数据，请手动添加产品");
};

// 提交表单（新增或编辑）
const submitForm = async () => {
  console.log("开始提交表单，当前模式:", isEditMode.value ? '编辑' : '新增');
  
  // 表单验证
  if (!allocationForm.value.allocateId) {
    ElMessage.error("调拨单号不能为空");
    return;
  }

  if (!allocationForm.value.orderNumber) {
    ElMessage.error("关联订单号不能为空");
    return;
  }

  if (!allocationForm.value.allocateWarehouseIn) {
    ElMessage.error("调拨仓库（入）不能为空");
    return;
  }

  if (!allocationForm.value.allocateWarehouseOut) {
    ElMessage.error("调拨仓库（出）不能为空");
    return;
  }

  if (allocationProductForm.value.length === 0) {
    ElMessage.error("请至少添加一个产品");
    return;
  }

  // 验证产品数量和ID
  for (const product of allocationProductForm.value) {
    if (!product.quantity || product.quantity <= 0) {
      ElMessage.error(`产品 ${product.productName} 的数量必须大于0`);
      return;
    }
    const actualProductId = product.productId || product.id;
    if (!actualProductId) {
      console.error("产品缺少ID详情:", product);
      ElMessage.error(
        `产品 ${product.productName} 缺少产品ID，请重新选择该产品`
      );
      return;
    }

    // 验证产品ID是否为有效数字
    const productId = Number(actualProductId);
    if (isNaN(productId) || productId <= 0) {
      console.error("产品ID无效:", actualProductId, "产品:", product);
      ElMessage.error(
        `产品 ${product.productName} 的产品ID无效 (${actualProductId})，请重新选择该产品`
      );
      return;
    }

    // 验证产品编码是否存在且不为空
    if (!product.productCode || product.productCode.trim() === "") {
      console.error("产品缺少编码或编码为空:", product);
      ElMessage.error(
        `产品 ${product.productName} 缺少有效的产品编码，请重新选择该产品`
      );
      return;
    }
  }

  // 构造统一的请求数据 - 新增和编辑使用相同的字段结构
  const requestData = {
    allocateId: String(allocationForm.value.allocateId),
    orderNumber: allocationForm.value.orderNumber,
    allocateWarehouseIn: allocationForm.value.allocateWarehouseIn,
    allocateWarehouseOut: allocationForm.value.allocateWarehouseOut,
    products: allocationProductForm.value.map((item) => ({
      productId: Number(item.productId || item.id) || 0,
      quantity: Number(item.quantity),
      productCode: item.productCode || "",
    })),
    note: allocationForm.value.note || "",
    orderCreator: allocationForm.value.orderCreator || "",
    orderCreatorTime: allocationForm.value.orderCreatorTime || new Date().toISOString(),
    manager: allocationForm.value.manager || "",
    managerTime: allocationForm.value.managerTime || null, // 如果为空则设为null，避免发送空字符串
    state: allocationForm.value.state || 0,
  };

  // 根据模式判断是新增还是编辑
  const apiUrl = isEditMode.value ? "/lssuewrite/api/Allocate/UpdateAllocateStatus" : "/lssuewrite/api/Allocate/CreateAllocate";
  const successMessage = isEditMode.value ? "调拨单更新成功" : "调拨单创建成功";

  try {
    console.log("提交调拨单数据:", requestData);
    console.log("产品列表详情:", allocationProductForm.value);
    console.log(`执行${isEditMode.value ? '编辑' : '新增'}操作，API地址:`, apiUrl);
    console.log("当前isEditMode值:", isEditMode.value);
    console.log("表单中的allocateId字段:", allocationForm.value.allocateId);
    console.log("发送请求到:", apiUrl);
    console.log("请求数据:", JSON.stringify(requestData, null, 2));

    // 详细检查每个产品的数据
    requestData.products.forEach((product, index) => {
      console.log(`产品 ${index + 1} 详细信息:`, {
        productId: product.productId,
        productCode: product.productCode,
        quantity: product.quantity,
        原始产品数据: allocationProductForm.value[index],
      });

      if (!product.productCode) {
        console.warn(`警告: 产品 ${index + 1} 的 productCode 为空`);
      }
      if (!product.productId || product.productId <= 0) {
        console.warn(
          `警告: 产品 ${index + 1} 的 productId 无效: ${product.productId}`
        );
      }
    });

    // 调用API
    const response = await http.post(apiUrl, requestData);

    console.log("API响应:", response.data);
    console.log("响应状态码:", response.status);
    console.log("响应头:", response.headers);

    // 修正成功判断逻辑：如果状态码是200，且响应体为空或包含成功指示，则视为成功
    if (response.status === 200 && (Object.keys(response.data).length === 0 || response.data.code === 200 || response.data.success)) {
      ElMessage.success(successMessage);
      

      
      closeDialog();
      ShowAllocation(); // 刷新列表
    } else {
      console.error("API返回错误:", response.data);
      ElMessage.error(response.data.message || `${isEditMode.value ? '更新' : '创建'}调拨单失败`);
    }
  } catch (error: any) {
    console.error(`${isEditMode.value ? '更新' : '创建'}调拨单失败:`, error);
    
    // 详细的错误处理和显示
    if (error.response) {
      // 服务器响应了错误状态码
      const status = error.response.status;
      const responseData = error.response.data;
      
      console.error("后端错误详情:", {
        status: status,
        data: responseData,
        url: error.config?.url,
        method: error.config?.method,
        requestData: error.config?.data
      });
      
      if (responseData && responseData.message) {
        ElMessage.error(`${isEditMode.value ? '更新' : '创建'}调拨单失败: ${responseData.message}`);
      } else if (responseData && responseData.errors) {
        // 处理验证错误
        const errorMessages = Object.values(responseData.errors).flat().join(', ');
        ElMessage.error(`验证失败: ${errorMessages}`);
      } else {
        ElMessage.error(`请求失败 (${status}): ${error.response.statusText}`);
      }
    } else if (error.request) {
      // 请求已发出但没有收到响应
      ElMessage.error("无法连接到服务器，请检查网络连接和服务器状态");
      console.error("网络错误:", error.request);
    } else {
      // 其他错误
      ElMessage.error(`${isEditMode.value ? '更新' : '创建'}调拨单失败: ${error.message}`);
    }
  }
};
// 产品选择弹框相关状态
const productDialogVisible = ref(false);
const productList = ref<Product[]>([]);
const selectedProducts = ref<Product[]>([]);

// 新增产品时调用接口获取产品数据（带重试机制）
const fetchProducts = async (event?: MouseEvent, retries: number = API_CONFIG.PRODUCT_API.retries) => {
  for (let attempt = 1; attempt <= retries; attempt++) {
    try {
      console.log(`尝试获取产品数据 (第${attempt}次)`);
      const response = await http.get("/basicread/api/Product/GetProduct");
      console.log("产品API返回数据:", response.data);

      let products = [];
      if (response.data && Array.isArray(response.data)) {
        products = response.data;
      } else if (response.data.data && Array.isArray(response.data.data)) {
        products = response.data.data;
      } else {
        productList.value = [];
        ElMessage.warning("产品数据格式异常");
        return;
      }

      // 处理产品数据，确保每个产品都有ID
      productList.value = products.map((product: any, index: number) => {
        // 尝试多种可能的ID字段，优先使用productId
        const productId =
          product.productId ||
          product.id ||
          product.Id ||
          product.ProductId ||
          index + 1;

        console.log(`产品 ${product.productName || product.name} 的ID处理:`, {
          原始数据: product,
          所有字段: Object.keys(product),
          productId字段: product.productId,
          id字段: product.id,
          Id字段: product.Id,
          ProductId字段: product.ProductId,
          最终使用ID: productId,
          ID是否有效: productId && productId !== index + 1,
        });

        return {
          ...product,
          id: productId, // 统一使用id字段存储
          productId: productId, // 同时保留productId字段
          // 补充可能缺失的字段
          productCode: product.productCode || product.code || `CODE${productId}`,
          productName: product.productName || product.name || `产品${productId}`,
          specifications: product.specifications || product.spec || product.unit || '个',
          stock: product.stock || product.inventory || product.stockQuantity || 0,
          locationName: product.locationName || product.location || product.warehouse || '默认库位',
          description: product.description || product.desc || product.remark || product.note || '暂无描述'
        };
      });

      console.log("处理后的产品列表:", productList.value);
      
      // 如果是编辑模式，自动勾选已有的产品
      if (isEditMode.value && allocationProductForm.value.length > 0) {
        autoSelectExistingProducts();
      }
      
      productDialogVisible.value = true;
      return; // 成功获取数据，退出重试循环
    } catch (error: any) {
      console.error(`获取产品数据失败 (第${attempt}次):`, error);

      // 如果是404错误且是最后一次尝试，尝试备用端点
      if (error.response?.status === 404 && attempt === retries) {
        console.log("主端点404，尝试备用端点...");
        const alternativeEndpoints = ["/basicread/api/Product/GetProducts", "/basicread/api/Products"];
        
        for (const endpoint of alternativeEndpoints) {
          const alternativeData = await tryAlternativeEndpoint(endpoint);
          if (alternativeData) {
            console.log(`备用端点 ${endpoint} 成功`);
            // 处理备用端点返回的数据
            let products = [];
            if (alternativeData && Array.isArray(alternativeData)) {
              products = alternativeData;
            } else if (alternativeData.data && Array.isArray(alternativeData.data)) {
              products = alternativeData.data;
            }
            
            if (products.length > 0) {
              // 使用与主端点相同的数据处理逻辑
              productList.value = products.map((product: any, index: number) => {
                const productId = product.productId || product.id || product.Id || product.ProductId || index + 1;
                return {
                  ...product,
                  id: productId,
                  productId: productId,
                  productCode: product.productCode || product.code || `CODE${productId}`,
                  productName: product.productName || product.name || `产品${productId}`,
                  specifications: product.specifications || product.spec || product.unit || '个',
                  stock: product.stock || product.inventory || product.stockQuantity || 0,
                  locationName: product.locationName || product.location || product.warehouse || '默认库位',
                  description: product.description || product.desc || product.remark || product.note || '暂无描述'
                };
              });
              
              // 如果是编辑模式，自动勾选已有的产品
              if (isEditMode.value && allocationProductForm.value.length > 0) {
                autoSelectExistingProducts();
              }
              
              productDialogVisible.value = true;
              return;
            }
          }
        }
      }
      
      // 使用统一的错误处理
      handleProductError(error, attempt, retries);
      
      // 如果不是最后一次尝试，等待后重试
      if (attempt < retries) {
        console.log(`等待${attempt * 1000}ms后重试...`);
        await new Promise(resolve => setTimeout(resolve, attempt * 1000));
      }
    }
  }
};

// 自动勾选已有的产品
const autoSelectExistingProducts = () => {
  console.log("开始自动勾选已有产品");
  console.log("当前调拨单中的产品:", allocationProductForm.value);
  console.log("产品列表:", productList.value);
  
  // 清空当前选择
  selectedProducts.value = [];
  
  // 遍历调拨单中的产品，在产品列表中查找匹配的产品并勾选
  allocationProductForm.value.forEach(existingProduct => {
    // 尝试多种匹配方式
    const matchedProduct = productList.value.find(product => {
      // 通过产品ID匹配
      if (existingProduct.productId && product.productId == existingProduct.productId) {
        return true;
      }
      if (existingProduct.id && product.id == existingProduct.id) {
        return true;
      }
      
      // 通过产品编码匹配
      if (existingProduct.productCode && product.productCode === existingProduct.productCode) {
        return true;
      }
      
      // 通过产品名称匹配
      if (existingProduct.productName && product.productName === existingProduct.productName) {
        return true;
      }
      
      return false;
    });
    
    if (matchedProduct) {
      console.log(`找到匹配产品: ${matchedProduct.productName} (${matchedProduct.productCode})`);
      selectedProducts.value.push(matchedProduct);
    } else {
      console.log(`未找到匹配产品: ${existingProduct.productName} (${existingProduct.productCode})`);
    }
  });
  
  console.log(`自动勾选了 ${selectedProducts.value.length} 个产品`);
};

// 验证产品ID是否有效
const validateProductId = (product: Product) => {
  const productName = product.productName || product.name || "未知产品";

  // 检查是否有任何形式的ID
  const hasAnyId =
    product.id || product.productId || product.Id || product.ProductId;

  if (!hasAnyId) {
    console.error("产品完全缺少ID字段:", {
      产品名称: productName,
      原始数据: product,
      所有字段: Object.keys(product),
    });
    return false;
  }

  // 检查ID是否为有效值（不是临时分配的索引ID）
  const actualId =
    product.productId || product.id || product.Id || product.ProductId;
  if (!actualId || Number(actualId) <= 0) {
    console.error("产品ID无效:", {
      产品名称: productName,
      ID值: actualId,
      原始数据: product,
    });
    return false;
  }

  return true;
};

// 确认选择产品
const confirmSelectProducts = () => {
  const addedCount = selectedProducts.value.length;
  let actualAddedCount = 0;
  let invalidProducts: string[] = [];

  // 如果是编辑模式，先清空现有产品列表
  if (isEditMode.value) {
    allocationProductForm.value = [];
  }

  selectedProducts.value.forEach((product: Product) => {
    const productName = product.productName || product.name || "未知产品";

    // 验证产品ID
    if (!validateProductId(product)) {
      invalidProducts.push(productName);
      return;
    }

    // 检查是否已存在相同产品（仅在非编辑模式下）
    if (!isEditMode.value) {
      const exists = allocationProductForm.value.find(
        (item) =>
          item.productCode === (product.productCode || product.code) ||
          item.id === product.id
      );

      if (exists) {
        console.log("产品已存在，跳过:", product.productName || product.name);
        return;
      }
    }

    const newProduct = {
      productName: product.productName || product.name || `产品${product.id}`,
      productCode: product.productCode || product.code || `CODE${product.id}`,
      specifications: product.specifications || product.spec || product.unit || "个",
      price: product.price || product.unitPrice || 0,
      quantity: 1,
      locationName: product.locationName || product.location || product.warehouse || "默认库位",
      id: product.id, // 前端显示用的ID
      productId: product.productId || product.id, // 后端API需要的productId
    };

    console.log("添加产品到调拨单:", newProduct);
    console.log("原始产品数据:", product);

    // 验证关键字段
    if (!newProduct.productCode || newProduct.productCode.trim() === "") {
      console.error("警告: 添加的产品缺少有效的productCode", {
        产品名称: newProduct.productName,
        原始productCode: product.productCode,
        原始code: product.code,
        最终productCode: newProduct.productCode,
      });
    }

    allocationProductForm.value.push(newProduct);
    actualAddedCount++;
  });

  selectedProducts.value = [];
  productDialogVisible.value = false;

  // 提供详细的反馈信息
  if (invalidProducts.length > 0) {
    ElMessage.error(
      `以下产品缺少有效的产品ID，无法添加：${invalidProducts.join(", ")}`
    );
    console.error("无效产品列表:", invalidProducts);
  }

  if (actualAddedCount > 0) {
    const modeText = isEditMode.value ? '更新' : '添加';
    ElMessage.success(`已成功${modeText} ${actualAddedCount} 个产品`);
  } else if (addedCount > 0 && invalidProducts.length === 0) {
    if (!isEditMode.value) {
      ElMessage.warning("所选产品已存在，未添加新产品");
    } else {
      ElMessage.warning("未选择任何新产品");
    }
  } else if (addedCount === 0) {
    ElMessage.warning("未选择任何产品");
  }
};

// 取消选择产品
const cancelSelectProducts = () => {
  selectedProducts.value = [];
  productDialogVisible.value = false;
  
  // 如果是编辑模式，提示用户
  if (isEditMode.value) {
    ElMessage.info("已取消产品选择，调拨单中的产品保持不变");
  }
};

// 从调拨单中移除产品
const removeProductFromForm = (index: number) => {
  ElMessageBox.confirm("确定要删除这个产品吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      allocationProductForm.value.splice(index, 1);
      ElMessage.success("产品已删除");
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 查看弹框方法
const viewDialog = async (row: any) => {
  console.log("查看弹框接收到的行数据:", row);
  viewData.value = {
    ...row,
    // 确保所有需要的字段都有默认值
    allocateId: row.allocateId || "-",
    state: row.state !== undefined ? row.state : 0,
    orderNumber: row.orderNumber || "-",
            orderCreator: row.orderCreator || row.manager || "-", // 如果没有制单人，使用审核人
        orderCreatorTime: row.orderCreatorTime || row.managerTime || "-",
    note: row.note || "无",
    auditReason: row.auditReason || "同意",
  };

  // 保存主表格行数据，用于补充API中缺失的字段
  const mainTableRowData = row;

  ShowAllocationProductForView(row.allocateId, mainTableRowData);
  
  // 加载记录数据
  console.log("=== 开始加载记录数据 ===");
  console.log("调拨单号:", row.allocateId);
  console.log("关联订单号:", row.orderNumber);
  try {
    await loadRecordData(row.allocateId, row.orderNumber);
    console.log("=== 记录数据加载完成 ===");
    console.log("出库记录数量:", outboundRecords.value.length);
    console.log("入库记录数量:", inboundRecords.value.length);
  } catch (error) {
    console.error("加载记录数据时出错:", error);
  }
  
  console.log("查看弹框 - 操作记录数据:", operationRecords.value);
  console.log("查看弹框 - 操作记录数量:", operationRecords.value.length);
  
  viewDialogVisible.value = true;
};

// 加载记录数据
const loadRecordData = async (allocateId: string, orderNumber: string) => {
  try {
    console.log("=== 开始加载记录数据 ===");
    console.log("调拨单号:", allocateId);
    console.log("关联订单号:", orderNumber);
    
    // 加载出库记录
    console.log("开始加载出库记录...");
    try {
      console.log("获取所有出库记录...");
      const outboundResponse = await http.get("/reads/api/Inventory/Getchuku");
      console.log("出库记录API响应:", outboundResponse.data);
      
      if (outboundResponse.data.code === 200) {
        const data = outboundResponse.data.data || [];
        console.log("出库记录原始数据:", data);
        console.log("出库记录数量:", data.length);
        
        outboundRecords.value = data;
        console.log("出库记录加载完成，最终数量:", outboundRecords.value.length);
      }
    } catch (error) {
      console.log("出库记录加载失败:", error);
      outboundRecords.value = [];
    }

    // 加载入库记录
    console.log("开始加载入库记录...");
    try {
      console.log("获取所有入库记录...");
      const inboundResponse = await http.get("/reads/api/Inventory/GetOutbound");
      console.log("入库记录API响应:", inboundResponse.data);
      
      if (inboundResponse.data.code === 200) {
        const data = inboundResponse.data.data || [];
        console.log("入库记录原始数据:", data);
        console.log("入库记录数量:", data.length);
        
        inboundRecords.value = data;
        console.log("入库记录加载完成，最终数量:", inboundRecords.value.length);
      }
    } catch (error) {
      console.log("入库记录加载失败:", error);
      inboundRecords.value = [];
    }

    // 加载操作记录
    console.log("开始加载操作记录...");
    try {
      await loadOperationRecords(allocateId);
      console.log("操作记录加载完成");
    } catch (error) {
      console.log("操作记录加载失败:", error);
    }
    
    console.log("=== 记录数据加载完成 ===");
  } catch (error) {
    console.error("加载记录数据失败:", error);
  }
};

// 关闭查看弹框
const closeViewDialog = () => {
  viewDialogVisible.value = false;
  viewData.value = {};
  viewProductData.value = [];
  outboundRecords.value = [];
  inboundRecords.value = [];
  operationRecords.value = [];
  activeTab.value = 'products';
};

// 获取查看弹框的产品数据
const ShowAllocationProductForView = (
  allocateId: string,
  mainTableRowData?: any
) => {
  console.log("获取产品数据，调拨单号:", allocateId);
  console.log("主表格数据:", mainTableRowData);
  
  // 直接尝试从原始数据中获取该调拨单的所有产品
  const tryGetProductData = async () => {
    console.log("从原始数据获取产品信息");
    
    // 尝试获取该调拨单的所有原始产品数据
    const getAllProductsForAllocate = async () => {
      try {
        // 获取所有调拨单数据（不去重）
        const response = await http.get("/lssueread/api/Allocate/GetAllocate", {
          params: {
            PageIndex: 1,
            PageSize: 1000, // 获取足够多的数据
            AllocateId: allocateId,
          },
        });
        
        console.log("获取原始调拨单数据:", response.data);
        const rawList = response.data.pageDatas || [];
        
                 // 筛选出属于当前调拨单的所有产品
         const productsForThisAllocate = rawList.filter((item: any) => item.allocateId === allocateId);
        console.log(`找到 ${productsForThisAllocate.length} 个产品属于调拨单 ${allocateId}`);
        
        if (productsForThisAllocate.length > 0) {
          // 将原始数据转换为产品显示格式
          viewProductData.value = productsForThisAllocate.map((item: any, index: number) => ({
            productCode: item.productCode || item.code || `CP${index + 1}`,
            productName: item.productName || item.name || `产品${index + 1}`,
            specifications: item.specifications || item.spec || "个",
            batch: item.batch || "20156852",
            quantity: item.quantity || "1",
            currentLocation: item.locationName || item.depotName || "默认库位",
            targetLocation: item.allocateWarehouseIn || "3号仓库",
          }));
          console.log("从原始数据创建的产品列表:", viewProductData.value);
          return;
        }
      } catch (error) {
        console.error("获取原始数据失败:", error);
      }
      
      // 如果还是无法获取，使用主表格数据创建备用数据
      if (mainTableRowData) {
        const fallbackData = [
          {
            productCode: mainTableRowData.productCode || "CP001",
            productName: mainTableRowData.productName || "默认产品",
            specifications: mainTableRowData.specifications || "个",
            batch: "20156852",
            quantity: mainTableRowData.quantity || "1",
            currentLocation: mainTableRowData.locationName || mainTableRowData.depotName || "默认库位",
            targetLocation: mainTableRowData.allocateWarehouseIn || "3号仓库",
          },
        ];
        console.log("使用主表格备用数据:", fallbackData);
        viewProductData.value = fallbackData;
      } else {
        console.log("没有主表格数据，显示空数据");
        viewProductData.value = [];
      }
    };
    
    await getAllProductsForAllocate();
  };
  
  tryGetProductData();
};

// 格式化日期
const formatDate = (dateString: string | undefined) => {
  if (!dateString) return "-";
  try {
    const date = new Date(dateString);
    return date.toLocaleString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
    });
  } catch (error) {
    return dateString;
  }
};

// 创建出库记录
const createOutboundRecord = async (row: any) => {
  // 权限验证：只有制单人才能出库
  if (!canOutboundInbound(row)) {
    ElMessage.error("您没有权限进行出库操作，只有制单人才能出库");
    return;
  }
  
  // 检查状态：驳回的调拨单无法出库
  if (row.state === 2) {
    ElMessage.error("驳回的调拨单无法进行出库操作");
    return;
  }
  
  try {
    const currentUser = getCurrentUser();
    const outboundData = {
      allocateId: row.allocateId,
      outboundDate: new Date().toISOString(),
      quantity: row.quantity,
      outboundWarehouse: row.depotName || "主仓库",
      outboundLocation: row.locationName || "A区-01-01",
      outboundOperator: currentUser, // 使用当前登录用户
      note: "正常出库"
    };

    const response = await http.post("/write/api/Allocate/CreateOutboundRecord", outboundData);
    
    if (response.data.code === 200) {
      ElMessage.success("出库记录创建成功");
      

      
      ShowAllocation(); // 刷新列表
    } else {
      ElMessage.error(response.data.message || "出库记录创建失败");
    }
  } catch (error: any) {
    console.error("创建出库记录失败:", error);
    ElMessage.error("出库记录创建失败，请重试");
  }
};

// 创建入库记录
const createInboundRecord = async (row: any) => {
  // 权限验证：只有制单人才能入库
  if (!canOutboundInbound(row)) {
    ElMessage.error("您没有权限进行入库操作，只有制单人才能入库");
    return;
  }
  
  // 检查状态：驳回的调拨单无法入库
  if (row.state === 2) {
    ElMessage.error("驳回的调拨单无法进行入库操作");
    return;
  }
  
  try {
    const currentUser = getCurrentUser();
    const inboundData = {
      allocateId: row.allocateId,
      inboundDate: new Date().toISOString(),
      quantity: row.quantity,
      inboundWarehouse: row.allocateWarehouseIn || "分仓库",
      inboundLocation: "C区-03-01",
      inboundOperator: currentUser, // 使用当前登录用户
      note: "正常入库"
    };

    const response = await http.post("/write/api/Allocate/CreateInboundRecord", inboundData);
    
    if (response.data.code === 200) {
      ElMessage.success("入库记录创建成功");
      

      
      ShowAllocation(); // 刷新列表
    } else {
      ElMessage.error(response.data.message || "入库记录创建失败");
    }
  } catch (error: any) {
    console.error("创建入库记录失败:", error);
    ElMessage.error("入库记录创建失败，请重试");
  }
};

// 获取当前登录用户
const getCurrentUser = () => {
  // 优先从 Pinia store 获取
  if (counterStore.Account.name) {
    return counterStore.Account.name;
  }
  // 备用方案：从 localStorage 获取
  const storedUser = localStorage.getItem('currentUser');
  return storedUser || '未知用户';
};

// 判断用户是否有权限编辑或删除某个调拨单
const canEditOrDelete = (row: any) => {
  // 如果状态是已审核（state == 1）或驳回（state == 2），则所有人都无法编辑删除
  if (row.state === 1 || row.state === 2) {
    return false;
  }
  
  const currentUser = getCurrentUser();
  const orderCreator = row.orderCreator || row.OrderCreator || '';
  return currentUser === orderCreator;
};

// 判断用户是否有权限进行出库入库操作
const canOutboundInbound = (row: any) => {
  const currentUser = getCurrentUser();
  const orderCreator = row.orderCreator || row.OrderCreator || '';
  return currentUser === orderCreator;
};

// 获取当前用户的 rid
const userRid = computed(() => {
  return counterStore.Account.rid || 0;
});

// 调试操作记录
const debugOperationRecords = async () => {
  console.log("=== 调试操作记录 ===");
  console.log("当前调拨单号:", viewData.value.allocateId);
  console.log("当前操作记录数据:", operationRecords.value);
  console.log("操作记录数量:", operationRecords.value.length);
  console.log("筛选后的操作记录:", filteredOperationRecords.value);
  console.log("筛选后的记录数量:", filteredOperationRecords.value.length);
  console.log("分页信息:", operationPagination.value);
  console.log("筛选条件:", operationFilter.value);
  
  // 添加测试数据
  console.log("添加测试数据...");
  operationRecords.value = [
    {
      id: 1,
      operator: "张三",
      allocateId: "105246",
      operationType: "审批",
      operationContent: "好",
      createTime: "2025-08-07T10:53:17",
      isDel: false
    },
    {
      id: 2,
      operator: "admin",
      allocateId: "105218",
      operationType: "新增",
      operationContent: "好东西",
      createTime: "2025-08-07T10:52:31",
      isDel: false
    },
    {
      id: 3,
      operator: "李四",
      allocateId: "105219",
      operationType: "修改",
      operationContent: "更新信息",
      createTime: "2025-08-07T11:00:00",
      isDel: false
    }
  ];
  
  // 更新筛选后的数据
  filteredOperationRecords.value = [...operationRecords.value];
  operationPagination.value.totalCount = operationRecords.value.length;
  
  console.log("测试数据已添加，数量:", operationRecords.value.length);
  console.log("筛选后数据已更新");
  
  // 强制更新视图
  await nextTick();
  console.log("视图已更新");
  
  if (viewData.value.allocateId) {
    console.log("重新获取操作记录...");
    const logs = await getOperationLogs(viewData.value.allocateId, 1, 50);
    console.log("重新获取的结果:", logs);
    if (logs) {
      operationRecords.value = Array.isArray(logs) ? logs : [];
      filteredOperationRecords.value = [...operationRecords.value];
      operationPagination.value.totalCount = operationRecords.value.length;
      console.log("更新后的操作记录:", operationRecords.value);
      console.log("更新后的筛选记录:", filteredOperationRecords.value);
    }
  }
};

// 搜索操作记录
const searchOperationRecords = () => {
  console.log("搜索操作记录，筛选条件:", operationFilter.value);
  
  // 重置分页到第一页
  operationPagination.value.currentPage = 1;
  
  // 应用筛选条件
  applyOperationFilter();
};

// 获取筛选后的总记录数
const getFilteredTotalCount = () => {
  if (!operationRecords.value || operationRecords.value.length === 0) {
    return 0;
  }
  
  let filtered = [...operationRecords.value];
  
  // 按操作类型筛选
  if (operationFilter.value.operationType) {
    filtered = filtered.filter(record => 
      record.operationType === operationFilter.value.operationType
    );
  }
  
  // 按操作人筛选
  if (operationFilter.value.operator) {
    filtered = filtered.filter(record => 
      record.operator && record.operator.toLowerCase().includes(operationFilter.value.operator.toLowerCase())
    );
  }
  
  // 按操作时间筛选
  if (operationFilter.value.operationTime) {
    const filterTime = new Date(operationFilter.value.operationTime);
    filtered = filtered.filter(record => {
      if (!record.createTime) return false;
      const recordTime = new Date(record.createTime);
      // 筛选同一天的操作记录
      return filterTime.toDateString() === recordTime.toDateString();
    });
  }
  
  return filtered.length;
};

// 应用操作记录筛选
const applyOperationFilter = () => {
  if (!operationRecords.value || operationRecords.value.length === 0) {
    filteredOperationRecords.value = [];
    return;
  }
  
  let filtered = [...operationRecords.value];
  
  // 按操作类型筛选
  if (operationFilter.value.operationType) {
    filtered = filtered.filter(record => 
      record.operationType === operationFilter.value.operationType
    );
  }
  
  // 按操作人筛选
  if (operationFilter.value.operator) {
    filtered = filtered.filter(record => 
      record.operator && record.operator.toLowerCase().includes(operationFilter.value.operator.toLowerCase())
    );
  }
  
  // 按操作时间筛选
  if (operationFilter.value.operationTime) {
    const filterTime = new Date(operationFilter.value.operationTime);
    filtered = filtered.filter(record => {
      if (!record.createTime) return false;
      const recordTime = new Date(record.createTime);
      // 筛选同一天的操作记录
      return filterTime.toDateString() === recordTime.toDateString();
    });
  }
  
  // 应用分页
  const startIndex = (operationPagination.value.currentPage - 1) * operationPagination.value.pageSize;
  const endIndex = startIndex + operationPagination.value.pageSize;
  const paginatedData = filtered.slice(startIndex, endIndex);
  
  filteredOperationRecords.value = paginatedData;
  console.log(`筛选完成，原始记录: ${operationRecords.value.length}, 筛选后: ${filtered.length}, 当前页显示: ${paginatedData.length}`);
};

// 重置操作记录筛选
const resetOperationFilter = () => {
  operationFilter.value = {
    operationType: '',
    operator: '',
    operationTime: ''
  };
  
  // 重置分页到第一页
  operationPagination.value.currentPage = 1;
  
  // 重新应用筛选（显示所有记录）
  applyOperationFilter();
  
  console.log("筛选条件已重置，显示所有记录");
};

// 操作记录分页处理
const handleOperationPageChange = (page: number) => {
  operationPagination.value.currentPage = page;
  // 重新应用筛选和分页
  applyOperationFilter();
  console.log(`操作记录分页切换到第 ${page} 页`);
};

const handleOperationSizeChange = (size: number) => {
  operationPagination.value.pageSize = size;
  operationPagination.value.currentPage = 1;
  // 重新应用筛选和分页
  applyOperationFilter();
  console.log(`操作记录分页大小调整为 ${size}`);
};

// 加载操作记录
const loadOperationRecords = async (allocateId: string) => {
  try {
    operationRecordsLoading.value = true;
    console.log(`加载操作记录，调拨单号: ${allocateId}`);
    
    // 获取所有操作记录（不分页）
    const logs = await getOperationLogs(allocateId, 1, 1000);
    
    console.log("getOperationLogs返回结果:", logs);
    console.log("logs类型:", typeof logs);
    console.log("logs是否为数组:", Array.isArray(logs));
    
    if (logs && Array.isArray(logs)) {
      operationRecords.value = logs;
      console.log(`成功加载操作记录，数量: ${logs.length}`);
      console.log("操作记录数据:", operationRecords.value);
      
      // 重置分页到第一页
      operationPagination.value.currentPage = 1;
      
      // 加载完成后自动应用筛选和分页
      applyOperationFilter();
    } else {
      operationRecords.value = [];
      filteredOperationRecords.value = [];
      console.log("操作记录为空或格式异常");
    }
  } catch (error) {
    console.error("加载操作记录失败:", error);
    operationRecords.value = [];
    filteredOperationRecords.value = [];
  } finally {
    operationRecordsLoading.value = false;
  }
};

// 获取操作记录
const getOperationLogs = async (allocateId: string, pageIndex: number = 1, pageSize: number = 1000) => {
  console.log(`获取操作记录，调拨单号: ${allocateId}, 页码: ${pageIndex}, 页大小: ${pageSize}`);
  
  try {
    // 调用操作记录API，使用正确的路径和参数
    const response = await http.get("/lssueread/api/Allocate/GetAllocateOperationLogCommand", {
      params: {
        PageIndex: pageIndex,
        PageSize: pageSize
      }
    });
    
    console.log("操作记录API响应:", response.data);
    
    if (response.data.code === 200) {
      const responseData = response.data;
      console.log("解析到的操作记录响应:", responseData);
      
      // 处理数据部分
      let records = [];
      if (Array.isArray(responseData.pageDatas)) {
        records = responseData.pageDatas;
      } else if (Array.isArray(responseData.data)) {
        records = responseData.data;
      } else if (responseData.data && Array.isArray(responseData.data.pageDatas)) {
        records = responseData.data.pageDatas;
      } else {
        console.warn("操作记录数据格式异常:", responseData);
        return [];
      }
      
      console.log("最终解析的操作记录:", records);
      return records;
    } else {
      console.error("获取操作记录失败:", response.data.message);
      return [];
    }
  } catch (error) {
    console.error("获取操作记录失败:", error);
    return [];
  }
};

// 获取状态信息
const getStatusInfo = async (statusCode: number) => {
  try {
    const response = await http.get("/lssueread/api/Allocate/GetAllocateStatus", {
      params: { StatusCode: statusCode }
    });
    
    if (response.data.code === 200) {
      const statusData = response.data.data;
      ElMessageBox.alert(
        `<div>
          <p><strong>状态名称:</strong> ${statusData.statusName}</p>
          <p><strong>状态描述:</strong> ${statusData.statusDescription}</p>
          <p><strong>是否可操作:</strong> ${statusData.isOperable ? '是' : '否'}</p>
          <p><strong>下一步操作:</strong> ${statusData.nextOperations?.join(', ') || '无'}</p>
        </div>`,
        '状态详情',
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定'
        }
      );
    } else {
      ElMessage.error("获取状态信息失败");
    }
  } catch (error) {
    console.error("获取状态信息失败:", error);
    ElMessage.error("获取状态信息失败");
  }
};

// 通用记录导出函数
const exportRecords = (records: any[], recordType: string, dataMapper: (record: any, index: number) => any) => {
  if (records.length === 0) {
    ElMessage.warning(`暂无${recordType}可导出`);
    return;
  }

  try {
    const exportData = records.map(dataMapper);
    const fileName = `${recordType}_${viewData.value.allocateId || '调拨单'}_${new Date().toISOString().slice(0, 10)}.xlsx`;
    exportToExcel(exportData, fileName, recordType);
    ElMessage.success(`${recordType}导出成功`);
  } catch (error) {
    console.error(`导出${recordType}失败:`, error);
    ElMessage.error("导出失败，请重试");
  }
};

// 调试出库记录
const debugOutboundRecords = async () => {
  console.log("=== 调试出库记录 ===");
  console.log("当前出库记录数量:", outboundRecords.value.length);
  console.log("当前出库记录数据:", outboundRecords.value);
  
  try {
    console.log("重新获取所有出库记录...");
    const response = await http.get("/reads/api/Inventory/Getchuku");
    console.log("出库记录API响应:", response.data);
    
    if (response.data.code === 200) {
      const data = response.data.data || [];
      console.log("出库记录总数:", data.length);
      console.log("出库记录数据:", data);
      
      outboundRecords.value = data;
      ElMessage.success(`加载了 ${data.length} 条出库记录`);
    }
  } catch (error) {
    console.error("调试出库记录失败:", error);
    ElMessage.error("调试失败");
  }
};

// 导出出库记录
const exportOutboundRecords = () => {
  exportRecords(outboundRecords.value, '出库记录', (record, index) => ({
    '序号': index + 1,
    '关联订单号': record.associatedOrderNumber || '-',
    '制单人': record.preparedName || '-',
    '制单时间': formatDate(record.preparedTime) || '-',
    '产品名称': record.productName || '-',
    '商品单价': record.price || 0,
    '库存数量': record.incomingQuantity || '-',
    '仓库名称': record.depotName || '-'
  }));
};

// 调试入库记录
const debugInboundRecords = async () => {
  console.log("=== 调试入库记录 ===");
  console.log("当前入库记录数量:", inboundRecords.value.length);
  console.log("当前入库记录数据:", inboundRecords.value);
  
  try {
    console.log("重新获取所有入库记录...");
    const response = await http.get("/reads/api/Inventory/GetOutbound");
    console.log("入库记录API响应:", response.data);
    
    if (response.data.code === 200) {
      const data = response.data.data || [];
      console.log("入库记录总数:", data.length);
      console.log("入库记录数据:", data);
      
      inboundRecords.value = data;
      ElMessage.success(`加载了 ${data.length} 条入库记录`);
    }
  } catch (error) {
    console.error("调试入库记录失败:", error);
    ElMessage.error("调试失败");
  }
};

// 导出入库记录
const exportInboundRecords = () => {
  exportRecords(inboundRecords.value, '入库记录', (record, index) => ({
    '序号': index + 1,
    '关联订单号': record.associatedOrderNumber || '-',
    '制单人': record.preparedName || '-',
    '制单时间': formatDate(record.preparedTime) || '-',
    '产品名称': record.productName || '-',
    '商品单价': record.price || 0,
    '库存数量': record.incomingQuantity || '-',
    '仓库名称': record.depotName || '-'
  }));
};

// 导出操作记录
const exportOperationRecords = () => {
  // 导出筛选后的数据
  const dataToExport = filteredOperationRecords.value.length > 0 ? filteredOperationRecords.value : operationRecords.value;
  const exportType = filteredOperationRecords.value.length > 0 ? '筛选后的操作记录' : '操作记录';
  
  exportRecords(dataToExport, exportType, (record, index) => ({
    '序号': index + 1,
    '操作人': record.operator || '-',
    '操作类型': record.operationType || '-',
    '操作内容描述': record.operationContent || '-',
    '操作时间': formatDate(record.createTime) || '-'
  }));
};



// 通用Excel导出函数
const exportToExcel = (data: any[], fileName: string, sheetName: string) => {
  // 如果没有安装xlsx库，使用CSV导出作为备选方案
  if (typeof window.XLSX === 'undefined') {
    exportToCSV(data, fileName.replace('.xlsx', '.csv'));
    return;
  }

  try {
    // 创建工作簿
    const wb = window.XLSX.utils.book_new();
    
    // 创建工作表
    const ws = window.XLSX.utils.json_to_sheet(data);
    
    // 设置列宽
    const colWidths = Object.keys(data[0] || {}).map(key => ({
      wch: Math.max(key.length, 15)
    }));
    ws['!cols'] = colWidths;
    
    // 添加工作表到工作簿
    window.XLSX.utils.book_append_sheet(wb, ws, sheetName);
    
    // 导出文件
    window.XLSX.writeFile(wb, fileName);
  } catch (error) {
    console.error("Excel导出失败，使用CSV导出:", error);
    exportToCSV(data, fileName.replace('.xlsx', '.csv'));
  }
};

// CSV导出函数
const exportToCSV = (data: any[], fileName: string) => {
  try {
    if (data.length === 0) {
      ElMessage.warning("没有数据可导出");
      return;
    }

    // 获取表头
    const headers = Object.keys(data[0]);
    
    // 生成CSV内容
    const csvContent = [
      headers.join(','), // 表头
      ...data.map(row => 
        headers.map(header => {
          const value = row[header];
          // 如果值包含逗号、引号或换行符，需要用引号包围
          if (typeof value === 'string' && (value.includes(',') || value.includes('"') || value.includes('\n'))) {
            return `"${value.replace(/"/g, '""')}"`;
          }
          return value;
        }).join(',')
      )
    ].join('\n');

    // 添加BOM以支持中文
    const BOM = '\uFEFF';
    const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' });
    
    // 创建下载链接
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', fileName);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    
    ElMessage.success("CSV文件导出成功");
  } catch (error) {
    console.error("CSV导出失败:", error);
    ElMessage.error("导出失败，请重试");
  }
};

// 导出产品信息
const exportProductInfo = () => {
  if (viewProductData.value.length === 0) {
    ElMessage.warning("暂无产品信息可导出");
    return;
  }

  try {
    // 准备导出数据
    const exportData = viewProductData.value.map((item, index) => ({
      '序号': index + 1,
      '产品编码': item.productCode || '-',
      '产品名称': item.productName || '-',
      '规格': item.specifications || '-',
      '批次': item.batch || '-',
      '数量': item.quantity || '-',
      '当前库位': item.currentLocation || '-',
      '调拨仓库': item.targetLocation || '-',
      '调拨单号': viewData.value.allocateId || '-',
      '关联订单号': viewData.value.orderNumber || '-',
      '制单人': viewData.value.orderCreator || '-',
      '制单时间': formatDate(viewData.value.orderCreatorTime) || '-',
      '备注': viewData.value.note || '-'
    }));

    // 生成文件名
    const fileName = `产品信息_${viewData.value.allocateId || '调拨单'}_${new Date().toISOString().slice(0, 10)}.xlsx`;

    // 调用导出函数
    exportToExcel(exportData, fileName, '产品信息');
    
    ElMessage.success("产品信息导出成功");
  } catch (error) {
    console.error("导出产品信息失败:", error);
    ElMessage.error("导出失败，请重试");
  }
};

// 导出完整报告
const exportCompleteReport = () => {
  try {
    // 检查是否有数据可导出
    const hasProductData = viewProductData.value.length > 0;
    const hasOutboundData = outboundRecords.value.length > 0;
    const hasInboundData = inboundRecords.value.length > 0;
    const hasOperationData = operationRecords.value.length > 0;

    if (!hasProductData && !hasOutboundData && !hasInboundData && !hasOperationData) {
      ElMessage.warning("暂无数据可导出");
      return;
    }

    // 如果没有安装xlsx库，使用CSV导出
    if (typeof window.XLSX === 'undefined') {
      exportCompleteReportToCSV();
      return;
    }

    // 创建工作簿
    const wb = window.XLSX.utils.book_new();

    // 1. 调拨单基本信息
    const basicInfo = [
      {
        '调拨单号': viewData.value.allocateId || '-',
        '关联订单号': viewData.value.orderNumber || '-',
        '制单人': viewData.value.orderCreator || '-',
        '制单时间': formatDate(viewData.value.orderCreatorTime) || '-',
        '审核人': viewData.value.manager || '-',
        '审核时间': formatDate(viewData.value.managerTime) || '-',
        '单据状态': getStatusLabel(viewData.value.state),
        '备注': viewData.value.note || '-',
        '审核原因': viewData.value.auditReason || '-'
      }
    ];
    const wsBasic = window.XLSX.utils.json_to_sheet(basicInfo);
    window.XLSX.utils.book_append_sheet(wb, wsBasic, '调拨单信息');

    // 2. 产品信息
    if (hasProductData) {
      const productData = viewProductData.value.map((item, index) => ({
        '序号': index + 1,
        '产品编码': item.productCode || '-',
        '产品名称': item.productName || '-',
        '规格': item.specifications || '-',
        '批次': item.batch || '-',
        '数量': item.quantity || '-',
        '当前库位': item.currentLocation || '-',
        '调拨仓库': item.targetLocation || '-'
      }));
      const wsProduct = window.XLSX.utils.json_to_sheet(productData);
      window.XLSX.utils.book_append_sheet(wb, wsProduct, '产品信息');
    }

    // 3. 出库记录
    if (hasOutboundData) {
      const outboundData = outboundRecords.value.map((record, index) => ({
        '序号': index + 1,
        '关联订单号': record.associatedOrderNumber || '-',
        '制单人': record.preparedName || '-',
        '制单时间': formatDate(record.preparedTime) || '-',
        '产品名称': record.productName || '-',
        '商品单价': record.price || 0,
        '库存数量': record.incomingQuantity || '-',
        '仓库名称': record.depotName || '-'
      }));
      const wsOutbound = window.XLSX.utils.json_to_sheet(outboundData);
      window.XLSX.utils.book_append_sheet(wb, wsOutbound, '出库记录');
    }

    // 4. 入库记录
    if (hasInboundData) {
      const inboundData = inboundRecords.value.map((record, index) => ({
        '序号': index + 1,
        '关联订单号': record.associatedOrderNumber || '-',
        '制单人': record.preparedName || '-',
        '制单时间': formatDate(record.preparedTime) || '-',
        '产品名称': record.productName || '-',
        '商品单价': record.price || 0,
        '库存数量': record.incomingQuantity || '-',
        '仓库名称': record.depotName || '-'
      }));
      const wsInbound = window.XLSX.utils.json_to_sheet(inboundData);
      window.XLSX.utils.book_append_sheet(wb, wsInbound, '入库记录');
    }

    // 5. 操作记录
    if (hasOperationData) {
      const operationData = operationRecords.value.map((record, index) => ({
        '序号': index + 1,
        '操作记录ID': record.id || '-',
        '操作时间': formatDate(record.createTime) || '-',
        '操作人': record.operator || '-',
        '操作类型': record.operationType || '-',
        '操作内容': record.operationContent || '-',
        '调拨单号': record.allocateId || '-',
        '是否删除': record.isDel ? '是' : '否'
      }));
      const wsOperation = window.XLSX.utils.json_to_sheet(operationData);
      window.XLSX.utils.book_append_sheet(wb, wsOperation, '操作记录');
    }

    // 导出文件
    const fileName = `调拨单完整报告_${viewData.value.allocateId || '调拨单'}_${new Date().toISOString().slice(0, 10)}.xlsx`;
    window.XLSX.writeFile(wb, fileName);

    ElMessage.success("完整报告导出成功");
  } catch (error) {
    console.error("导出完整报告失败:", error);
    ElMessage.error("导出失败，请重试");
  }
};

// 获取状态标签
const getStatusLabel = (state: number | undefined) => {
  if (state === undefined) return '-';
  const statusOption = statusOptions.find(s => s.value == String(state));
  return statusOption ? statusOption.label : String(state);
};

// 导出完整报告到CSV（备选方案）
const exportCompleteReportToCSV = () => {
  try {
    const reportData = [];
    
    // 添加调拨单基本信息
    reportData.push(['调拨单完整报告']);
    reportData.push([]);
    reportData.push(['调拨单号', viewData.value.allocateId || '-']);
    reportData.push(['关联订单号', viewData.value.orderNumber || '-']);
    reportData.push(['制单人', viewData.value.orderCreator || '-']);
    reportData.push(['制单时间', formatDate(viewData.value.orderCreatorTime) || '-']);
    reportData.push(['审核人', viewData.value.manager || '-']);
    reportData.push(['审核时间', formatDate(viewData.value.managerTime) || '-']);
    reportData.push(['单据状态', getStatusLabel(viewData.value.state)]);
    reportData.push(['备注', viewData.value.note || '-']);
    reportData.push([]);

    // 添加产品信息
    if (viewProductData.value.length > 0) {
      reportData.push(['产品信息']);
      reportData.push(['序号', '产品编码', '产品名称', '规格', '批次', '数量', '当前库位', '调拨仓库']);
      viewProductData.value.forEach((item, index) => {
        reportData.push([
          index + 1,
          item.productCode || '-',
          item.productName || '-',
          item.specifications || '-',
          item.batch || '-',
          item.quantity || '-',
          item.currentLocation || '-',
          item.targetLocation || '-'
        ]);
      });
      reportData.push([]);
    }

    // 添加出库记录
    if (outboundRecords.value.length > 0) {
      reportData.push(['出库记录']);
      reportData.push(['序号', '关联订单号', '制单人', '制单时间', '产品名称', '商品单价', '库存数量', '仓库名称']);
      outboundRecords.value.forEach((record, index) => {
        reportData.push([
          index + 1,
          record.associatedOrderNumber || '-',
          record.preparedName || '-',
          formatDate(record.preparedTime) || '-',
          record.productName || '-',
          record.price || 0,
          record.incomingQuantity || '-',
          record.depotName || '-'
        ]);
      });
      reportData.push([]);
    }

    // 添加入库记录
    if (inboundRecords.value.length > 0) {
      reportData.push(['入库记录']);
      reportData.push(['序号', '关联订单号', '制单人', '制单时间', '产品名称', '商品单价', '库存数量', '仓库名称']);
      inboundRecords.value.forEach((record, index) => {
        reportData.push([
          index + 1,
          record.associatedOrderNumber || '-',
          record.preparedName || '-',
          formatDate(record.preparedTime) || '-',
          record.productName || '-',
          record.price || 0,
          record.incomingQuantity || '-',
          record.depotName || '-'
        ]);
      });
      reportData.push([]);
    }

    // 添加操作记录
    if (operationRecords.value.length > 0) {
      reportData.push(['操作记录']);
      reportData.push(['序号', '操作记录ID', '操作时间', '操作人', '操作类型', '操作内容', '调拨单号', '是否删除']);
      operationRecords.value.forEach((record, index) => {
        reportData.push([
          index + 1,
          record.id || '-',
          formatDate(record.createTime) || '-',
          record.operator || '-',
          record.operationType || '-',
          record.operationContent || '-',
          record.allocateId || '-',
          record.isDel ? '是' : '否'
        ]);
      });
    }

    // 生成CSV内容
    const csvContent = reportData.map(row => 
      row.map(cell => {
        if (typeof cell === 'string' && (cell.includes(',') || cell.includes('"') || cell.includes('\n'))) {
          return `"${cell.replace(/"/g, '""')}"`;
        }
        return cell;
      }).join(',')
    ).join('\n');

    // 添加BOM以支持中文
    const BOM = '\uFEFF';
    const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' });
    
    // 创建下载链接
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', `调拨单完整报告_${viewData.value.allocateId || '调拨单'}_${new Date().toISOString().slice(0, 10)}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    
    ElMessage.success("完整报告CSV文件导出成功");
  } catch (error) {
    console.error("导出完整报告CSV失败:", error);
    ElMessage.error("导出失败，请重试");
  }
};

// 审批弹框相关
const approveDialogVisible = ref(false);
const approveDialogRow = ref<any>(null);
const approveRemark = ref("");

const openApproveDialog = (row: any) => {
  approveDialogRow.value = row;
  approveRemark.value = "";
  approveDialogVisible.value = true;
};

const approveAllocation = () => {
  // 在这里添加审批逻辑
  console.log("审批调拨单:", approveDialogRow.value);
  console.log("审批备注:", approveRemark.value);
  approveDialogVisible.value = false;
};

const handleApprove = async (type: 'agree' | 'reject') => {
  if (!approveDialogRow.value) return;
  
  const row = approveDialogRow.value;
  const state = type === 'agree' ? 1 : 2;
  
  // 获取当前审批人
  const currentUser = getCurrentUser();
  const currentTime = new Date().toISOString();
  
  // 使用新的API格式，包含审批人和审批时间
  const requestData = {
    allocateId: row.allocateId,
    orderCreator: row.orderCreator || '',
    note: approveRemark.value || '',
    manager: currentUser, // 审批人
    managerTime: currentTime, // 审批时间
    state: state
  };
  
  console.log('审批请求数据:', requestData);
  
  try {
    const res = await http.post('/lssuewrite/api/Allocate/ApproveAllocate', requestData);
    console.log('审批响应:', res.data);
    
    if (res.data && (res.data.code === 200 || res.data.success)) {
      ElMessage.success(type === 'agree' ? '审批通过' : '已驳回');
      approveDialogVisible.value = false;
      filter.value.State = "";
      ShowAllocation();
    } else {
      ElMessage.error(res.data.message || '审批失败');
    }
  } catch (e) {
    console.error('审批请求失败:', e);
    ElMessage.error('审批请求失败');
  }
};
</script>




<style scoped>









.allocation-page {
  background: #f5f6fa;
  min-height: 100vh;
  padding: 20px;
}

.filter-card {
  margin-bottom: 18px;
}

.filter-title {
  font-weight: bold;
  font-size: 15px;
  margin-bottom: 8px;
}

.filter-form {
  margin-top: 8px;
}

.table-card {
  padding-bottom: 0;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0;
}

.table-title {
  font-weight: bold;
  font-size: 15px;
}

.table-actions {
  display: flex;
  gap: 8px;
}

.table-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.batch-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.el-table th,
.el-table td {
  text-align: center;
}

/* 查看弹框样式 */
.view-dialog-content {
  padding: 0;
}

.info-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.info-row {
  display: flex;
  margin-bottom: 15px;
  align-items: center;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-item {
  flex: 1;
  display: flex;
  align-items: center;
  margin-right: 30px;
}

.info-item:last-child {
  margin-right: 0;
}

.info-item.full-width {
  flex: 1;
  margin-right: 0;
}

.info-label {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
  margin-right: 10px;
}

.info-value {
  color: #303133;
  word-break: break-all;
}

.product-section {
  margin-top: 10px;
}

.dialog-footer {
  text-align: center;
}

/* 弹框表格样式 */
:deep(.el-dialog .el-table) {
  font-size: 12px;
}

:deep(.el-dialog .el-table th) {
  background-color: #f5f7fa;
  font-weight: 500;
  font-size: 12px;
  padding: 8px 0;
}

:deep(.el-dialog .el-table td) {
  padding: 6px 0;
  font-size: 12px;
}

/* 记录表格统一样式 - 使用更高优先级的选择器 */
:deep(.el-dialog .el-tabs .el-table) {
  font-size: 12px !important;
}

:deep(.el-dialog .el-tabs .el-table th) {
  background-color: #f5f7fa !important;
  font-weight: 500 !important;
  text-align: center !important;
  color: #606266 !important;
  font-size: 12px !important;
  padding: 8px 0 !important;
}

:deep(.el-dialog .el-tabs .el-table td) {
  padding: 6px 0 !important;
  text-align: center !important;
  border-bottom: 1px solid #ebeef5 !important;
  font-size: 12px !important;
}

/* 确保所有表格都有统一的边框和间距 */
:deep(.el-dialog .el-table) {
  border-radius: 4px !important;
  overflow: hidden !important;
}

:deep(.el-dialog .el-table th) {
  background-color: #f5f7fa !important;
  font-weight: 500 !important;
  color: #606266 !important;
  text-align: center !important;
  font-size: 12px !important;
}

:deep(.el-dialog .el-table td) {
  border-bottom: 1px solid #ebeef5 !important;
  text-align: center !important;
  font-size: 12px !important;
}

/* 强制覆盖Element Plus默认样式 */
/* 表格样式统一 */
:deep(.el-table) {
  border: 1px solid #ebeef5 !important;
  border-radius: 4px !important;
  table-layout: auto !important;
}

:deep(.el-table th) {
  background-color: #fafafa !important;
  border-bottom: 1px solid #ebeef5 !important;
  text-align: center !important;
}

:deep(.el-table td) {
  border-bottom: 1px solid #ebeef5 !important;
  text-align: center !important;
}

:deep(.el-table .cell) {
  text-align: center !important;
  white-space: nowrap !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
}

/* 自定义记录表格样式 */
.record-table {
  font-size: 12px !important;
}

.record-table :deep(th) {
  background-color: #f5f7fa !important;
  font-weight: 500 !important;
  color: #606266 !important;
  font-size: 12px !important;
  padding: 8px 0 !important;
}

.record-table :deep(td) {
  padding: 6px 0 !important;
  border-bottom: 1px solid #ebeef5 !important;
  font-size: 12px !important;
}

/* 操作记录表格专用样式 - 匹配图片样式 */
.operation-record-table {
  font-size: 12px !important;
  border: 1px solid #ebeef5 !important;
  border-radius: 4px !important;
}

.operation-record-table :deep(.el-table__header-wrapper) {
  background-color: #fafafa !important;
}

.operation-record-table :deep(.el-table__header th) {
  background-color: #fafafa !important;
  font-weight: 500 !important;
  color: #606266 !important;
  font-size: 12px !important;
  padding: 8px 0 !important;
  text-align: center !important;
  border-bottom: 1px solid #ebeef5 !important;
}

.operation-record-table :deep(.el-table__body td) {
  padding: 8px 0 !important;
  text-align: center !important;
  border-bottom: 1px solid #ebeef5 !important;
  font-size: 12px !important;
  color: #303133 !important;
}

.operation-record-table :deep(.el-table__body tr:hover) {
  background-color: #f5f7fa !important;
}

.operation-record-table :deep(.el-table__body tr:nth-child(even)) {
  background-color: #fafafa !important;
}

.operation-record-table :deep(.el-table__body tr:nth-child(odd)) {
  background-color: #ffffff !important;
}

/* 确保表格边框清晰 */
.operation-record-table :deep(.el-table) {
  border: 1px solid #ebeef5 !important;
  border-radius: 4px !important;
  overflow: hidden !important;
}

.operation-record-table :deep(.el-table__inner-wrapper) {
  border: none !important;
}

.operation-record-table :deep(.el-table__header) {
  border-bottom: 1px solid #ebeef5 !important;
}

.operation-record-table :deep(.el-table__body) {
  border: none !important;
}

/* 确保表格在弹框中正确显示 */
:deep(.el-dialog .el-table) {
  margin: 0 !important;
}

:deep(.el-table .el-table__body-wrapper) {
  overflow-x: auto !important;
}

/* 确保最后一列可以拉伸到边框 */
:deep(.el-table .el-table__body-wrapper .el-table__body) {
  width: 100% !important;
}

:deep(.el-table .el-table__header-wrapper .el-table__header) {
  width: 100% !important;
}

/* 操作链接样式优化 */
.action-link {
  font-size: 12px;
  margin-left: 6px;
}

.action-link:first-child {
  margin-left: 0;
}
</style>
